<template>
  <van-form class="mt-4 mx-2" validate-first @submit="onSubmit" ref="form">
    <van-field
      v-if="mobile_origin"
      label="原手机号"
      :value="mobile_origin"
      readonly
    />
    <van-field
      v-model="mobile"
      name="mobile"
      ref="mobile"
      required
      label="手机号"
      placeholder="请输入手机号"
      :rules="[{ pattern, message: '手机号格式错误', trigger: 'onBlur' }]"
    />
    <van-field
      v-model="sms"
      name="sms"
      :rules="[{ required: true, message: '请输入短信验证码' }]"
      center
      clearable
      label="短信验证码"
      placeholder="请输入短信验证码"
    >
      <template #button>
        <van-button
          :loading="$loading"
          :disabled="smsDisable"
          native-type="button"
          @click.stop="sendSms"
          size="small"
          type="primary"
          class="w-24"
          >{{ smsSendBtnText }}</van-button
        >
      </template>
    </van-field>

    <div class="mt-6 mx-4">
      <van-button
        :loading="$loading"
        round
        block
        type="primary"
        native-type="submit"
        >提 交</van-button
      >
    </div>
  </van-form>
</template>

<script>
export default {
  data() {
    return {
      mobile: '',
      sms: '',
      pattern: /^[1][3,4,5,7,8,9][0-9]{9}$/,
      smsDisable: false,
      smsSendBtnText: '发送验证码',
      seconds: 60,
    }
  },
  computed: {
    mobile_origin() {
      return this.$store.state.user.mobile
    },
  },
  methods: {
    // 校验函数返回 true 表示校验通过，false 表示不通过
    validator(val) {
      return val && val === this.password
    },
    sendSms() {
      this.$refs.mobile.validate().then(_ => {
        this.smsDisable = true
        let tik = setInterval(() => {
          this.smsSendBtnText = `${this.seconds} 秒`
          this.seconds--
          if (this.seconds === 0) {
            clearInterval(tik)
            this.smsDisable = false
            this.seconds = 60
            this.smsSendBtnText = '发送验证码'
          }
        }, 1000)

        this.axios.post('/sms/code', { mobile: this.mobile }).then(res => {
          if (res.data.data.msg === 'OK') {
            this.$toast.success('发送成功')
          }
        })
      })
    },
    onSubmit() {
      this.axios
        .post(`/mobile/bind`, {
          mobile: this.mobile,
          code: this.sms,
        })
        .then(res => {
          if (res.data.code === 1) {
            this.$toast.success('绑定成功')
            this.$router.back()
          } else {
            this.$toast.fail(res.data.msg)
          }
        })
    },
  },
}
</script>

<style>
</style>